<template>
  <div>
    <BasicTable
      @register="registerTable"
      rowKey="id"
      :rowSelection="{ type: 'checkbox' }"
    >
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">
          {{ t('新增配置') }}
        </a-button>
        <a-button
          v-if="getSelectRowKeys().length > 0"
          type="error"
          @click="handleDeleteBatch"
        >
          {{ t('删除') }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:download-outlined',
              label: '下载',
              onClick: handleStartCodeGen.bind(null, record.id, 'download'),
            },
            {
              icon: 'ant-design:caret-right-filled',
              label: '生成本地代码',
              loading: createLoading,
              onClick: handleStartCodeGen.bind(null, record.id, 'toPath'),
            },
            {
              icon: 'clarity:note-edit-line',
              label: '编辑主配置',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              label: '编辑列配置',
              onClick: handleColumnEdit.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              label: '预览',
              onClick: handlePreview.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: t('是否确认删除'),
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <EditDrawer @register="registerDrawer" @success="handleSuccess" />
    <CodePreview @register="registerModal" />
    <ColumnsConfig @register="registerColumnDrawer" />
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'CodeGen',
});
</script>

<script lang="ts" setup>
import { ref } from 'vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import {
  page,
  del,
  runDownCodeGen,
  runLocalCodeGen,
} from '@/api/sys/dev/codeGenManager';
import { useDrawer } from '@/components/Drawer';
import { useModal } from '@/components/Modal';
import CodePreview from './CodePreview.vue';
import EditDrawer from './EditDrawer.vue';
import ColumnsConfig from './ColumnsConfig.vue';
import { useMessage } from '@/hooks/web/useMessage';
import { columns, searchFormSchema } from './data';
import { useI18n } from '@/hooks/web/useI18n';
const { t } = useI18n();
const createLoading = ref(false);
const { createMessage, createConfirm } = useMessage();
const [registerDrawer, { openDrawer }] = useDrawer();
const [registerColumnDrawer, { openDrawer: openColumnDrawer }] = useDrawer();
const [registerModal, { openModal }] = useModal();
const [registerTable, { reload, getSelectRowKeys }] = useTable({
  title: t('配置列表'),
  api: page,
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
  },
  useSearchForm: true,
  showTableSetting: false,
  clickToRowSelect: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 600,
    title: t('操作'),
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
});
function handleCreate() {
  openDrawer(true, {
    isUpdate: false,
  });
}
// /Users/frank/Documents/2023/framework/back/frame-back
const genDownLoad = async (id: string) => {
  const res = await runDownCodeGen(id);
  const filename = res.headers['content-disposition'];
  const blob = new Blob([res.data]);
  let downloadElement = document.createElement('a');
  const href = window.URL.createObjectURL(blob);
  downloadElement.href = href;
  downloadElement.download = decodeURIComponent(filename.split('filename=')[1]);
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
  window.URL.revokeObjectURL(href);
};
const genLocal = async (id: string) => {
  createLoading.value = true;
  const res = await runLocalCodeGen(id).catch(
    () => (createLoading.value = false)
  );
  createLoading.value = false;
  return res;
};
async function handleStartCodeGen(id: string, type: string) {
  if (type === 'download') {
    genDownLoad(id);
  } else {
    genLocal(id);
  }
}

function handleEdit(record: Recordable) {
  openDrawer(true, {
    record,
    isUpdate: true,
  });
}
function handleColumnEdit(record: Recordable) {
  openColumnDrawer(true, record.id);
}
function handlePreview(record: Recordable) {
  openModal(true, {
    id: record.id,
  });
}

function handleDeleteBatch() {
  createConfirm({
    iconType: 'warning',
    title: t('确认删除'),
    content: t('是否确认删除？'),
    onOk: async () => {
      del(getSelectRowKeys()).then(() => {
        createMessage.success(t('删除成功'));
        reload();
      });
    },
  });
}
function handleDelete(record: Recordable) {
  createConfirm({
    iconType: 'warning',
    title: t('确认删除'),
    content: t('是否确认删除？'),
    onOk: async () => {
      del([record.id]).then(() => {
        createMessage.success(t('删除成功'));
        reload();
      });
    },
  });
}

function handleSuccess() {
  reload();
}
</script>
